/*
 * IPhysicsEngine.cpp
 *
 *  Created on: 06.01.2012
 *      Author: Kirill Blinov
 *      Copyright: LGPL
 */

#include "IPhysicsEngine.h"

IPhysicsEngine::IPhysicsEngine( glm::vec3 FirstWorldCorner, glm::vec3 SecondWorldCorner, glm::vec3 Gravity )
{
    collisionConfiguration = new btDefaultCollisionConfiguration();
    axisSweep = new btAxisSweep3( btVector3( FirstWorldCorner.x, FirstWorldCorner.y, FirstWorldCorner.z ),
    		                      btVector3( SecondWorldCorner.x, SecondWorldCorner.y, SecondWorldCorner.z ),
    		                      MAX_ENGINE_OBJECT_HANDLERS );

    dynamicsWorld = new btDiscreteDynamicsWorld( new btCollisionDispatcher(collisionConfiguration),
                                                 axisSweep,
                                                 new btSequentialImpulseConstraintSolver(),
                                                 collisionConfiguration);

    dynamicsWorld->setGravity( btVector3( Gravity.x, Gravity.y, Gravity.z ) );

}

IPhysicsEngine::~IPhysicsEngine()
{
    delete dynamicsWorld;
    delete collisionConfiguration;
    delete axisSweep;

}

void
IPhysicsEngine::StepSimulate()
{
	//TODO Implement with time-server
    /*clock_t CurentTime = clock();
    if ( lastTime != 0 )
    {
            dynamicsWorld->stepSimulation( CurentTime - lastTime, 3 );
    }
    lastTime = CurentTime;*/
}

//-----------------------------------//

CCommonBulletBasedEngine::CCommonBulletBasedEngine( glm::vec3 FirstWorldCorner,
		                                            glm::vec3 SecondWorldCorner,
		                                            glm::vec3 Gravity ) : IPhysicsEngine( FirstWorldCorner,
		                                            		                              SecondWorldCorner,
		                                            		                              Gravity)
{

}

CCommonBulletBasedEngine::~CCommonBulletBasedEngine()
{

}

/*
 * Very important - only rigid bodies are supported till now
 */
//TODO implement collision filtration
void
CCommonBulletBasedEngine::AddPhisicsObject( IPhysicsObject& Object )
{
	btRigidBody *Body = btRigidBody::upcast( Object.GetBody() );
	dynamicsWorld->addRigidBody( Body );
}

/*
 * Very important - only rigid bodies are supported till now
 */
void
CCommonBulletBasedEngine::RemovePhisicsObject( IPhysicsObject& Object )
{
	btRigidBody *Body = btRigidBody::upcast( Object.GetBody() );
	dynamicsWorld->removeRigidBody( Body );
}
